﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Casamiel.API.Application;
using Casamiel.API.Application.Models.Mall.Req;
using Casamiel.API.Application.Models.Store;
using Casamiel.API.Application.Services;
using Casamiel.Application;
using Casamiel.Application.Commands;
using Casamiel.Application.Commands.Store;
using Casamiel.Common;
using Casamiel.Common.Extensions;
using Casamiel.Domain.Entity;
using Casamiel.Domain.Request;
using Casamiel.Domain.Response;
using MediatR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using NLog;

// For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace Casamiel.API.Controllers.V2
{
	/// <summary>
	/// Store controller.
	/// </summary>
	[Produces("application/json")]
    [ApiVersion("2.0")]
    [Route("api/v{api-version:apiVersion}/Store")]
    [Authorize]
    [ApiController]
    [EnableCors("any")]
     public class StoreController : BaseController
    {
        private readonly IStoreService _storeService;
        private readonly IStoreApiService _storeApiService;
        private readonly IIcApiService _icApiService;
        private readonly NLog.ILogger logger = LogManager.GetLogger("StoreService");
        private readonly IMediator _mediator;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="storeService"></param>
        /// <param name="storeApiService"></param>
        /// <param name="iicApiService"></param>
        /// <param name="mediator"></param>
        public StoreController(IStoreService storeService, IStoreApiService storeApiService, IIcApiService iicApiService, IMediator mediator)
        {
            _storeService = storeService;
            _storeApiService = storeApiService;
            _icApiService = iicApiService;
            _mediator = mediator;
        }
        /// <summary>
        /// 扫门店二维码
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        /// <remarks>{"qrcode":"xxxxxxxxxxxxxx"}</remarks>
        [HttpPost]
        [Route("[action]")]
        public async Task<IActionResult> ShopQrcodequery([FromBody] JObject data)
        {
            if (data == null)
            {
                throw new ArgumentNullException(nameof(data));
            }

            var model = await _icApiService.IcQrcodeQuery("", "", data["qrcode"].ToString()).ConfigureAwait(false);
            return Ok(model);
        }
        /// <summary>
        /// 附近门店信息.
        /// </summary>
        /// <param name="data"></param>
        /// <returns>The all store.</returns>
        /// <remarks>
        /// 纬度 、经度、距离
        /// {"lat":30,"lng":12.02222,"distance":5.2}
        /// </remarks>
        [HttpPost]
        [Route("[action]")]
        public async Task<BaseResult<List<StoreEntity>>> GetAllStore([FromBody]GetAllStoreReq data)
        {
            if (data == null)
            {
                throw new ArgumentNullException(nameof(data));
            }

            logger.Trace($"GetAllStoreByStoreName:{JsonConvert.SerializeObject(data)}");

            var lat = data.Lat;
            var lng = data.Lng;

            var distance = data.Distance;
            if (distance > 5000) {
                distance = 5000;
            }
            var cmd = new GetListCommand(lat, lng, distance);
            var result = await _mediator.Send(cmd).ConfigureAwait(false);
            return result;

        }

        /// <summary>
        ///门店详情
        /// </summary>
        /// <returns>The detail.</returns>
        /// <param name="req">Req.</param>

        [HttpPost]
        [Route("[action]")]
        public async Task<BaseResult<StoreEntity>> GetDetail([FromBody]StoreReq req)
        {
            if (req == null)
            {
                throw new ArgumentNullException(nameof(req));
            }

            var entity = await _storeService.GetDetail<ICasaMielSession>(req.StoreId).ConfigureAwait(false);
            if (entity == null) {
                return new BaseResult<StoreEntity>(null, 999, "门店不存在");
            }
            return new BaseResult<StoreEntity>(entity, 0, "");
        }
        /// <summary>
        /// Gets the name of the all store by store.
        /// </summary>
        /// <returns>The all store by store name.</returns>
        /// <param name="data">Data.</param>
        [HttpPost]
        [Route("[action]")]
        public async Task<IActionResult> GetAllStoreByStoreName([FromBody] GetAllStoresReq data)
        {
            if (data == null)
            {
                throw new ArgumentNullException(nameof(data));
            }

            logger.Trace($"GetAllStoreByStoreName:{JsonConvert.SerializeObject(data)}");


            var cmd = new GetAllStoreByStoreNameCommand { lat = data.Lat, lng = data.Lng, pageIndex = data.PageIndex, pageSize = data.PageSize, storeName = data.StoreName };
            var result1 = await _mediator.Send(cmd).ConfigureAwait(false);
            var result = new { result1.Code, pageindex = result1.PageIndex, pagesize = result1.PageSize, result1.Total, result1.Content };

            return Ok(result);
            

        }

        /// <summary>
        /// Gets the name of the all stores by store.
        /// </summary>
        /// <returns>The all stores by store name.</returns>
        /// <param name="data">Data.</param>
        /// <remarks>
        /// {"storeName":"","pageIndex":"1","pageSize":"10","lat":30,"lng":12.02222}
        /// </remarks>
        [HttpPost]
        [Route("[action]")]
        public async Task<IActionResult> GetAllStoresByStoreName([FromBody] GetAllStoresByStoreNameReq data)
        {
            if (data == null)
            {
                throw new ArgumentNullException(nameof(data));
            }

            logger.Trace($"GetAllStoresByStoreName:{JsonConvert.SerializeObject(data)}");

            var lat = data.Lat;
            var lng = data.Lng;
            var pageIndex = data.PageIndex.ToInt32(1);
            var PageSize = data.PageSize.ToInt32(10);
            // logger.Trace($"GetAllStoreByStoreName:[{lat},{lng}]");
            //var list = await  _storeService.GetStoreByNameAsync<ICasaMielSession>(data["storeName"].ToString(), data["pageIndex"].ToInt32(1), data["pageSize"].ToInt32(10));
            //var result = new { code = 0, pageindex=list.PageIndex,pagesize=list.PageSize,total=list.Total,content = list.Data};
            //return new JsonResult(result);
            var list = await _storeService.GetAllStoreByNameAsync<ICasaMielSession>(data.StoreName).ConfigureAwait(false);
            list=list.Where(c => c.IsCakeShopClose == 0).ToList();
            var _count = list.Count;
            for (int i = 0; i < _count; i++) {
                list[i].Distance = DistanceHelper.GetDistance(lat, lng, list[i].Latitude, list[i].Longitude);// _commonService.MapService.GetGistance(a, new Map { lat=item.Latitude.ToDouble(0), lng=item.Longitude.ToDouble(0)});
            }

            
            var entity = list.OrderBy(p => p.Distance).ToList().Skip((pageIndex - 1) * PageSize).Take(PageSize);
            //var query = entity.Skip((pageindex-1) * pagesize).Take(pagesize);
            var result = new { code = 0, pageindex = pageIndex, pagesize = PageSize, total = list.Count, content = entity };
            return Ok(result);
        }
        /// <summary>
        /// Gets the slie list.
        /// </summary>
        /// <returns>The slie list.</returns>
        /// <param name="data">Data.</param>
        /// <remarks>{"code":"AppIndex"}</remarks>
        [HttpPost]
        [Route("[action]")]
        public async Task<IActionResult> GetSlideList([FromBody]GetBoothListReq data)
        {
            if (data == null)
            {
                throw new ArgumentNullException(nameof(data));
            }

            var entity = await _storeApiService.GetSlideListAsync(data.Code).ConfigureAwait(false);
            var result = new { code = 0, content = entity };
            return new JsonResult(result);
        }

        /// <summary>
        /// Gets the news by identifier.
        /// </summary>
        /// <returns>The news by identifier.</returns>
        /// <param name="data">Data.</param>
        /// <remarks>
        /// {"id":"1"}
        /// </remarks>
        [Route("[action]")]
        [HttpPost]
        public async Task<IActionResult> GetNewsById([FromBody] MWebIdReq data)
        {
            if (data == null)
            {
                throw new ArgumentNullException(nameof(data));
            }

            var entity = await _storeApiService.GetNewsById(data.Id).ConfigureAwait(false);
            var result = new { code = 0, content = entity };
            return new JsonResult(result);
        }

        /// <summary>
        /// 导航小程序
        /// </summary>
        /// <returns>The list for navigation.</returns>
        /// <param name="data">Data.</param>
        [Route("[action]")]
        [HttpPost]
        public async Task<PagingResultRsp<List<GetStoreListForNavigationRsp>>> GeListForNavigation([FromBody] GetAllStoresReq data)
        {
            if (data == null)
            {
                throw new ArgumentNullException(nameof(data));
            }

            var lat = data.Lat;
            var lng = data.Lng;
            // logger.Trace($"GetAllStoreByStoreName:[{lat},{lng}]");
            //var list = await  _storeService.GetStoreByNameAsync<ICasaMielSession>(data["storeName"].ToString(), data["pageIndex"].ToInt32(1), data["pageSize"].ToInt32(10));
            //var result = new { code = 0, pageindex=list.PageIndex,pagesize=list.PageSize,total=list.Total,content = list.Data};
            //return new JsonResult(result);
            var list = await _storeService.GetListAsync<ICasaMielSession>(data.StoreName).ConfigureAwait(false);
            var _count = list.Count;
            for (int i = 0; i < _count; i++) {
                list[i].Distance = DistanceHelper.GetDistance(lat, lng, list[i].Latitude, list[i].Longitude);// _commonService.MapService.GetGistance(a, new Map { lat=item.Latitude.ToDouble(0), lng=item.Longitude.ToDouble(0)});
            }

            if (data.PageIndex <= 0) {
                data.PageIndex = 1;
            }
            if (data.PageSize <= 0) {
                data.PageSize = 10;
            }
            var entity = list.OrderBy(p => p.Distance).ToList().Skip((data.PageIndex - 1) * data.PageSize).Take(data.PageSize);
            var dd = from x in entity
                     select (new GetStoreListForNavigationRsp {
                         StoreId = x.StoreId,
                         StoreName = x.StoreName,
                         Latitude = x.Latitude,
                         Longitude = x.Longitude,
                         Distance = x.Distance,
                         FullAddress = x.FullAddress,
                         ShopHours = x.ShopHours,
                         SubStoreName = x.SubStoreName,
                         Phone = x.Phone,
                         ProvinceId = x.ProvinceId,
                         CityId = x.CityId,
                         DistrictId = x.DistrictId

                     });

            var rsp = new PagingResultRsp<List<GetStoreListForNavigationRsp>>(dd.ToList(), data.PageIndex, data.PageSize, list.Count, 0, "");

            return rsp;
             
        }
    }
}
